package com.dsczs.servlet;

import com.dsczs.annotation.AutoWired;
import com.dsczs.annotation.Controller;
import com.dsczs.annotation.RequestMapping;
import com.dsczs.annotation.Service;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 〈一句话功能简述〉
 * 〈功能详细描述〉
 *
 * @author 18047102
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class DispatcherServlet extends HttpServlet {

    private Properties properties = new Properties();

    private List<String> classNames = new ArrayList<>();

    private Map<String, Object> ioc = new HashMap<>();

    private Map<String, Method> handlerMapping = new HashMap<>();

    private Map<String, Object> controllerMap = new HashMap<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
       service(req,resp);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)  {
        try {
            doDispatcher(req,resp);
        } catch (Exception e) {
            try {
                resp.getWriter().write("500 error");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    private void doDispatcher(HttpServletRequest req, HttpServletResponse resp){
        if (handlerMapping.isEmpty()){
            return;
        }

        String url = req.getRequestURI();
        String contextPath = req.getContextPath();

        url = url.replace(contextPath, "").replaceAll("/+", "/");

        if (!this.handlerMapping.containsKey(url)){
            try {
                resp.getWriter().write("404 not found!");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        Method method = this.handlerMapping.get(url);

        Class<?>[] parameterTypes = method.getParameterTypes(); //获取方法的参数列表
        Map<String, String[]> parameterMap = req.getParameterMap(); //获取请求的参数

        //保存参数值
        Object[] paramValues = new Object[parameterTypes.length];

        //方法的参数列表
        for (int i = 0; i < parameterTypes.length; i++) {
            //根据参数名称，做某些处理
            String requestParam = parameterTypes[i].getSimpleName();

            if (requestParam.equals("HttpServletRequest")) {
                //参数类型已明确，这边强转类型
                paramValues[i] = req;
                continue;
            }
            if (requestParam.equals("HttpServletResponse")) {
                paramValues[i] = resp;
                continue;
            }
            if (requestParam.equals("String")) {
                for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
                    String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");
                    paramValues[i] = value;
                }
            }
        }
        //利用反射机制来调用
        try {
            method.invoke(this.controllerMap.get(url), paramValues);//obj是method所对应的实例 在ioc容器中
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  {
        service(req,resp);
    }

    @Override
    public void init(ServletConfig config)  {
        //1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //2.初始化所有相关联的类,扫描用户设定的包下面所有的类
        doScanner(properties.getProperty("scanPackage"));

        //3.拿到扫描到的类,通过反射机制,实例化,并且放到ioc容器中(k-v  beanName-bean) beanName默认是首字母小写
        doInstance();
        //4.初始化HandlerMapping(将url和method对应上)
        initHandlerMapping();
    }

    private void initHandlerMapping()  {
        if (ioc.isEmpty()){
            return;
        }
        for (Map.Entry<String,Object> entry:
             ioc.entrySet()) {
            Class<?> aClass = entry.getValue().getClass();
            Object obj = null;
            try {
                obj = aClass.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            Field[] fields = aClass.getDeclaredFields();//拿到类里面的属性
            if(!aClass.isAnnotationPresent(Controller.class)){
                continue;
            }

            for (Field field:
                 fields) {
                field.setAccessible(true);
                if(field.isAnnotationPresent(AutoWired.class)){
                    AutoWired annotation = field.getAnnotation(AutoWired.class);
                    String value = annotation.value();
                    if(value.equals("")){
                        value = field.getName().toLowerCase();
                    }
                    try {
                        System.out.println("111 -->  " + entry.getValue());
                        System.out.println("222 -->" + ioc.get(value));
                        field.set(obj,ioc.get(value));  //注意这里的obj 必须与 controllerMap中的obj一致，不然会导致控制器中的service注入失败
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }

            String baseUrl = "";
            if (aClass.isAnnotationPresent(RequestMapping.class)){
                RequestMapping annotation = aClass.getAnnotation(RequestMapping.class);
                baseUrl += annotation.value();
            }
            Method[] methods = aClass.getMethods();
            for (Method method:
                 methods) {
                if (!method.isAnnotationPresent(RequestMapping.class)){
                    continue;
                }

                RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                String url = annotation.value();
                url = (baseUrl + "/" + url).replaceAll("/+", "/");
                handlerMapping.put(url,method);
                controllerMap.put(url,obj);
                System.out.println(url + "," + method);
            }

        }
    }

    private void doInstance()  {
        if (classNames.isEmpty()){
            return;
        }
        for (String className :
                classNames) {
            Class<?> aClass = null;
            try {
                aClass = Class.forName(className);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            if (aClass.isAnnotationPresent(Controller.class)){
                Controller annotation = aClass.getAnnotation(Controller.class);
                if(ioc.get(annotation.value()) != null || ioc.get(aClass.getSimpleName().toLowerCase()) != null){
                   return;
                }
                if("".equals(annotation.value())){
                    try {
                        ioc.put(aClass.getSimpleName().toLowerCase(),aClass.newInstance());
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }else{
                    try {
                        ioc.put(annotation.value().toLowerCase(),aClass.newInstance());
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }else if(aClass.isAnnotationPresent(Service.class)){
                Service annotation = aClass.getAnnotation(Service.class);
                if(ioc.get(annotation.value()) != null || ioc.get(aClass.getSimpleName().toLowerCase()) != null){
                    return;
                }
                if("".equals(annotation.value())){
                    try {
                        ioc.put(aClass.getSimpleName().toLowerCase(),aClass.newInstance());
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                    }
                }else{
                    try {
                        ioc.put(annotation.value().toLowerCase(),aClass.newInstance());
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }else {
                continue;
            }
        }
    }

    private void doScanner(String scanPackage) {
//        URL resource = this.getClass().getClassLoader().getResource(File.separator + scanPackage.replaceAll("\\.", File.separator));
        URL resource = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File file = new File(resource.getFile());
        for (File f :
                file.listFiles()) {
            if (f.isDirectory()){
                doScanner(scanPackage + "." + f.getName());
            }else {
                String s = scanPackage + "." + f.getName().replace(".class", "");
                classNames.add(s);
            }
        }

    }

    private void doLoadConfig(String str) {
        if(str.startsWith("classpath:") || str.startsWith("classpath*:")){
            String[] location = str.split(":");
            str = location[1].trim();
        }
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(str);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != resourceAsStream){
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
